<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="680px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改套餐' : '添加日志'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15" class="flex-columns">
        <el-col :span="24">
          <el-form-item label="日志标题:" prop="logName">
            <el-input
              style="width: 230px;"
              clearable
              :maxlength="20"
              :disabled="isUpdate"
              v-model="form.logName"
              placeholder="请输入日志标题"
            />
          </el-form-item>
          <el-form-item label="版本号:" prop="logVersion">
            <div class="flex-between">
              <el-input
                style="width: 230px;"
                clearable
                :maxlength="20"
                v-model="form.logVersion"
                placeholder="请输入版本号"
              />
              <div class="m-left10">当前最新版本：{{logVersion}}</div>
            </div>
          </el-form-item>
        </el-col>
        <el-col style="padding: 0 10px">
          <!--v-if防止tinymce在弹框创建前创建-->
          <tinymce-editor
            v-if="visible"
            ref="editor"
            v-model="form.logUpdate"
            :init="option"
            :disabled="false"
          />
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import { emailReg, phoneReg } from 'ele-admin';
  import RoleSelect from './role-select.vue';
  import { mealAdd, mealUpdate, checkExistence } from '@/api/system/log';
  import {JSEncrypt} from "jsencrypt";
  import TinymceEditor from '@/components/TinymceEditor/index.vue';

  export default {
    components: { RoleSelect,TinymceEditor},
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      // 当前最新版本（旧）
      logVersion:String
    },
    data() {
      const defaultForm = {
        id:'',
        logName: '',
        logUpdate: '',
        logVersion: '',
        logImg: '',
      };
      return {
        option: {
          height: 520,
          // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
          file_picker_callback: (callback, _value, meta) => {
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            // 设定文件可选类型
            if (meta.filetype === 'image') {
              input.setAttribute('accept', 'image/*');
            } else if (meta.filetype === 'media') {
              input.setAttribute('accept', 'video/*');
            }
            input.onchange = () => {
              const file = input.files?.[0];
              if (!file) {
                return;
              }
              if (meta.filetype === 'media') {
                if (!file.type.startsWith('video/')) {
                  this.$refs.editor.alert({ content: '只能选择视频文件' });
                  return;
                }
              }
              if (file.size / 1024 / 1024 > 20) {
                this.$refs.editor.alert({ content: '大小不能超过 20MB' });
                return;
              }
              const reader = new FileReader();
              reader.onload = (e) => {
                if (e.target?.result != null) {
                  const blob = new Blob([e.target.result], { type: file.type });
                  callback(URL.createObjectURL(blob));
                }
              };
              reader.readAsArrayBuffer(file);
            };
            input.click();
          }
        },
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          logName: [
            {
              required: true,
              message: '请输入日志名称',
              trigger: 'blur'
            }
          ],
          logVersion: [
            {
              required: true,
              message: '请输入日志版本',
              trigger: 'blur'
            }
          ],
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          const data = {
            ...this.form,
          };
          const saveOrUpdate = this.isUpdate ? mealUpdate : mealAdd;
          if (!this.isUpdate) {
            let encryptor = new JSEncrypt()
            let pk = this.$store.state.signature.pk
            encryptor.setPublicKey(pk)
            data.password = encryptor.encrypt(data.password)
          }
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },
    watch: {
      visible(visible) {
        console.log("this.data",this.data)
        if (visible) {
          if (this.data) {
            this.$util.assignObject(this.form, {
              ...this.data,
              password: null,
              sex: this.data.sex + ''
            });
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
        console.log("this.form",this.form)

      }
    }
  };
</script>
